<template>
  <div class="content-section history-section">
    <div class="section-header">
      <h2 class="section-title">浏览记录</h2>
    </div>
    <div class="history-list" ref="historyList" @scroll="handleScroll">
      <n-grid x-gap="12" :cols="4">
        <n-gi
          v-for="item in dataList"
          :key="item.id"
          class="history-item"
          @click="viewCourse(item)"
        >
          <div class="course-cover-container">
            <img
              v-if="item.coverUrl"
              :src="item.coverUrl"
              :alt="item.courseTitle"
              class="course-cover"
              loading="lazy"
              decoding="async"
            />
            <div v-else class="no-image">
              <span>{{ item.courseTitle }}</span>
            </div>
          </div>
          <div class="course-info">
            <h4 class="course-title">{{ item.courseTitle }}</h4>
            <p class="course-author">{{ item.lecturerName || '官方' }}</p>
          </div>
        </n-gi>
      </n-grid>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 到底提示 -->
      <div v-if="isLastPage && dataList.length > 10" class="end-tip">
        <span>已经到底了</span>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && dataList.length === 0" class="empty-state"> 暂无浏览记录 </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { getHistoryListApi } from '@/api/course';
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';

  // ==================== 响应式数据 ====================
  const router = useRouter();
  const historyList = ref(null);

  // 查看课程详情
  const viewCourse = (course) => {
    router.push({
      name: 'Video',
      query: {
        courseId: course.courseId,
      },
    });
  };

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const dataList = ref<any[]>([]);

  async function loadData(isRefresh = false) {
    if (loading.value || (isLastPage.value && !isRefresh)) return;

    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
      };

      const data: any = await getHistoryListApi(params);

      let list = data.records || [];

      if (isRefresh) {
        dataList.value = list;
      } else {
        dataList.value = [...dataList.value, ...list];
      }

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value = data.current;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    dataList.value = [];
  }

  const handleScroll = () => {
    if (!historyList.value) return;

    const { scrollTop, scrollHeight, clientHeight } = historyList.value;

    // 当滚动到距离底部50px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadData();
    }
  };

  onMounted(() => {
    resetPage();
    loadData(true);
  });
</script>

<style lang="less">
  .history-list {
    max-height: 600px;
    overflow-y: auto;
    padding: 16px;
    // 优化滚动性能
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;

    .history-item {
      background: white;
      border-radius: 16px;
      overflow: hidden;
      border: 1px solid #f1f5f9;
      margin-bottom: 15px;
      // 优化渲染性能
      transform: translateZ(0);
      will-change: transform;
      contain: layout style paint;

      .course-cover-container {
        position: relative;
        overflow: hidden;

        .course-cover {
          width: 100%;
          height: 140px;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        &:hover .course-cover {
          transform: scale(1.05);
        }
      }

      .course-info {
        padding: 12px;

        .course-title {
          margin: 0 0 8px;
          font-size: 16px;
          font-weight: 600;
          color: #1e293b;
          line-height: 1.4;
          // 文本截断
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .course-author {
          margin: 0;
          color: #64748b;
          font-size: 14px;
          font-weight: 500;
          // 文本截断
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
</style>
